<?php

use Biz\cache\brand\Brand as cBrand;
use Biz\model\brandAccount\BrandAccountAuth;
use Biz\model\brandAccount\BrandAccountInfo;
use Biz\model\brandAccount\BrandAccountLog;
use Doraemon\model\Member as mMember;
use Doraemon\service\Member as sMember;
use Doraemon\tools\Log;

class SaveAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_REGISTER;

    public function main()
    {
        $uid = $this->uid;
        $id = $this->getRequest()->getPost('id', 0);
        $type = $this->getRequest()->getPost('type', '');
        $lockKey = 'brand:account:save:uid_' . $this->uid;
        $lock = cBrand::isLock($lockKey, 2);
        if ($lock) {
            throw new \Exception('操作过于频繁，请稍后再试');
        }
        if (empty($uid) && empty($type) && !in_array($type, BrandAccountInfo::ACCOUNT_TYPE)) {
            throw new \Exception('用户不存在或者类别为空');
        } else {
            $usedAccountId = BrandAccountInfo::getOneByWhere(['uid' => $uid, 'type' => $type, 'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED], 'id');
            $waitAuditInfo = $usedAccountId ? BrandAccountAuth::getOneByWhere(['account_id' => $usedAccountId, 'auth_status' => BrandAccountAuth::AUTH_STATUS_DEFAULT]) : [];
            if ($waitAuditInfo) {
                throw new \Exception('已经存在待审核的信息，请耐心等待管理员审核');
            }
            //数据组合
            $data = [
                'type' => $type,
                'nick' => $this->getRequest()->getPost('nick', ''),
                'company' => $this->getRequest()->getPost('company', ''),
                'credit_code' => $this->getRequest()->getPost('credit_code', ''),
                'name' => $this->getRequest()->getPost('name', ''),
                'phone' => $this->getRequest()->getPost('phone', ''),
                'email' => $this->getRequest()->getPost('email', ''),
                'weixin' => $this->getRequest()->getPost('weixin', ''),
                'license' => $this->getRequest()->getPost('license', ''),
                'license_time' => $this->getRequest()->getPost('license_time', ''),
                'letter' => $this->getRequest()->getPost('letter', ''),
                'letter_time' => $this->getRequest()->getPost('letter_time', ''),
                'certificate' => $this->getRequest()->getPost('certificate', ''),
                'application' => $this->getRequest()->getPost('application', ''),
                'authorization' => $this->getRequest()->getPost('authorization', ''),
                'shop' => $this->getRequest()->getPost('shop', ''),
            ];
            $data = array_filter($data);
            if (isset($data['shop']) && $data['shop']) {
                $shopArr = json_decode($data['shop'], true);
                if ($shopArr) {
                    foreach ($shopArr as &$row) {
                        $row['url'] = trim($row['url']);
                        $row['add_time'] = date('Y-m-d H:i:s');
                        $row['edit_time'] = date('Y-m-d H:i:s');
                    }
                    $data['shop'] = json_encode($shopArr, JSON_UNESCAPED_UNICODE);
                } else {
                    $data['shop'] = '';
                }
            }
            $accountInfo = BrandAccountInfo::getOneByWhere([
                'uid' => $uid,
                'type' => $type,
                'account_status[!]' => BrandAccountInfo::ACCOUNT_STATUS_DEL
            ]);
            if (isset($data['nick']) && $data['nick'] <> '') {
                $userInfo = mMember::getUser($uid);
                if (!in_array($accountInfo['account_status'], [BrandAccountInfo::ACCOUNT_STATUS_USED, BrandAccountInfo::ACCOUNT_STATUS_EXPIRE])) {
                    if ($userInfo && isset($userInfo['nick']) && ($userInfo['nick'] != $data['nick'])) {
                        $result = sMember::nick(false, true, $data['nick'], $uid, isset($userInfo['type']) ? $userInfo['type'] : '');
                        if ($result !== true && ($result !== '30天之内只能修改一次用户名' && $result !== '该昵称已被占用')) {
                            Log::info('昵称验证', compact('userInfo', 'result', 'data'));
                            throw new \Exception($result);
                        }
                    }
                }
            }
            $authInfo = [];
            if ($id) {
                $authInfo = BrandAccountAuth::getOneByWhere(['id' => $id, 'auth_status[!]' => BrandAccountAuth::AUTH_STATUS_DEL]);
                if (empty($authInfo)) {
                    Log::debug('查询不到有效的认证信息', compact('id', 'authInfo'));
                    throw new \Exception('参数错误');
                }
                if ($accountInfo && $accountInfo['id'] != $authInfo['account_id']) {
                    Log::debug('提交的认证信息对应的账户信息不一致', ['uid' => $uid, 'type' => $type, 'account_info' => $accountInfo, 'auth_info' => $authInfo]);
                    throw new \Exception('提交数据异常');
                }
            }
            if (empty($accountInfo)) {
                //创建一个账户信息
                $accountData = [
                    'uid' => $uid,
                    'type' => $type,
                    'nick' => $data['nick'],
                ];
                $accountId = BrandAccountInfo::insertData($accountData);
                BrandAccountLog::insertData([
                    'account_id' => $accountId,
                    'old_data' => '',
                    'new_data' => json_encode($accountData, JSON_UNESCAPED_UNICODE),
                    'operation' => BrandAccountLog::OPERATE_NEW_ACCOUNT,
                ]);
            } else {
                $accountId = $accountInfo['id'];
            }
            if (empty($accountId)) {
                Log::debug('没有账户id', compact('uid', 'type', 'accountId'));
                throw new \Exception('提交失败');
            }
            $data['account_id'] = $accountId;
            if ($id) {
                $data['auth_status'] = BrandAccountAuth::AUTH_STATUS_DEFAULT;
                $result = BrandAccountAuth::updateData($data, ['id' => $id]);
                BrandAccountLog::insertData([
                    'account_id' => $accountId,
                    'old_data' => json_encode($authInfo, JSON_UNESCAPED_UNICODE),
                    'new_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
                    'operation' => BrandAccountLog::OPERATE_USER_EDIT_AUTH,
                ]);
            } else {
                $id = BrandAccountAuth::insertData($data);
                BrandAccountLog::insertData([
                    'account_id' => $accountId,
                    'old_data' => '',
                    'new_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
                    'operation' => BrandAccountLog::OPERATE_USER_EDIT_AUTH,
                ]);
            }
            if ($id) {
                $this->afterSave($accountId);
                $this->setSuccess($result);
            } else {
                throw new \Exception('提交失败');
            }
        }
    }

    private function afterSave($accountId)
    {
        $accountInfo = BrandAccountInfo::getOneByWhere(['id' => $accountId]);
        if ($accountInfo && $accountInfo['account_status'] != BrandAccountInfo::ACCOUNT_STATUS_USED) {
            BrandAccountInfo::updateData(['auth_status' => BrandAccountInfo::AUTH_STATUS_DEFAULT], ['id' => $accountId]);
        }
    }
}